package python

import (
	"context"
	"gitee.com/kmyss/gf-ex/yscmd"
	"gitee.com/kmyss/gf-ex/yslog"
	"github.com/gogf/gf/v2/encoding/gcharset"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/gproc"
	"github.com/gogf/gf/v2/text/gstr"
)

const venvPath = "./venv"

func (s *sPython) initVenv(ctx context.Context) error {
	if s.hasVenv() {
		return gerror.New("已存在 venv 文件夹")
	}

	path := s.selectPython(ctx)
	yslog.Print("创建虚拟环境中...")
	err := gproc.ShellRun(ctx, path+" -m venv venv")
	if err != nil {
		yslog.Error("创建虚拟环境失败!")
		return err
	}

	return nil
}

func (s *sPython) selectPython(ctx context.Context) string {
	raw, err := gproc.ShellExec(ctx, "where python")
	if err != nil {
		return ""
	}
	utf8, _ := gcharset.UTF8To("gbk", raw)
	paths := gstr.SplitAndTrim(utf8, "\r\n")
	one, _ := yscmd.SelectOne(paths, "请选择一个 Python 版本")
	return one
}

// 检查是否有虚拟环境文件夹
func (s *sPython) hasVenv() bool {
	return gfile.Exists("./venv")
}
